package com.iman.manjusri.web.shop;

 
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iman.common.util.JsonMapper;
import com.iman.common.util.PaymentType;
import com.iman.common.util.PriceUtils;
import com.iman.manjusri.domain.User;
import com.iman.manjusri.mappers.models.DrmBuyOrder;
import com.iman.manjusri.mappers.models.DrmCourse;
import com.iman.manjusri.service.BuyCartService;
import com.iman.manjusri.service.BuyOrderService;
import com.iman.manjusri.service.CourseInfoService;
import com.iman.manjusri.service.PaymentService;
import com.iman.manjusri.service.SalesPromotionsService;
import com.iman.manjusri.service.UserService;
import com.iman.manjusri.vo.CalculateAmountVo;
import com.iman.manjusri.vo.DrmCourseVo;
import com.iman.manjusri.vo.SalesPromotionVo;
import com.iman.manjusri.vo.UserSInfoVo;
import com.iman.manjusri.web.BaseController;
/*
 * 
 */

/*
 * *************************************************************************
 * @文件名称: ShopController.java
 *
 * @包路径  : com.iman.manjusri.web.shop 
 *				 
 * @版权所有:   TSW   科技有限公司 (C) 2014
 *
 * @类描述:  
 * 
 * @创建人:   wangxiaolei  
 *
 * @创建时间: 2015年3月11日 - 上午12:46:52 
 *
 * @修改记录:
   -----------------------------------------------------------------------------------------------
             时间						|		修改人		|		修改的方法		|		修改描述                                                                
   -----------------------------------------------------------------------------------------------
							|					|					|                                       
   ----------------------------------------------------------------------------------------------- 	
 
 **************************************************************************
 */
@Controller
@RequestMapping(value="/shop/*")
public class ShopController  extends BaseController {

	@Autowired
	CourseInfoService courseInfoService;
	@Autowired
	SalesPromotionsService salesPromotionsService;
	@Autowired
	BuyCartService BuyCartService;
	@Autowired
	UserService userService;
	@Autowired
	BuyOrderService buyOrderService;
	@Autowired
	BuyCartService buyCartService;
	@Autowired
	PaymentService  paymentService;

	
	
	
	/**
	 * 
	 *  Function:
	 *  功能说明：  获取  一元钱，  抵   多少   学习币
	 *	 使用说明：。如果是零个，那就不抵；    
	 *  @author  wangxiaolei  DateTime 2015年8月26日 上午12:20:42
	 *	返回类型: int    
	 *  @param request
	 *  @return
	 */
	@RequestMapping(value = "/studycoin")
	@ResponseBody
	public int getStudycoin(HttpServletRequest request ) {
		return this.BuyCartService.get1YuanRMBTransferStudyCoin();
	}
	
	
	
	 /**
	  * 
	  *  Function:
	  *  功能说明：  点击购物车后进入页面
	  *	 使用说明：
	  *  @author  wangxiaolei  DateTime 2015年3月11日 上午12:47:30
	  *	返回类型: ModelAndView    
	  *  @param request
	  *  @return
	  */
	@RequestMapping(value = "/cart")
	public ModelAndView index(HttpServletRequest request, ModelMap model) {
		ModelAndView view = new ModelAndView("shop/shop");

		Long userId = super.getUserIdInSession(request);
		List<DrmCourseVo> list = this.BuyCartService.getCartWithCourse(userId);

		// 多个课程信息
		view.addObject("courseInfos", list);
		// 增加 活动
		// view.addObject("promotion", getCurrentSalesPromotionJson());
		// 学习币
		view.addObject("coin", getCurrentUserCoin(userId));

		putResourceSrc(view);
		return view;
	}

	public static final BigDecimal B100 = BigDecimal.valueOf(100);
	
	@RequestMapping(value = "/calculateAmount")
	@ResponseBody
	public CalculateAmountVo calculateAmount(HttpServletRequest request,
			@RequestParam(value = "cartId[]") Long cartId[], boolean useCredit) {
		Long userId = super.getUserIdInSession(request);
		CalculateAmountVo result = new CalculateAmountVo();

		List<DrmCourse> courses = courseInfoService.getCourseByCartIds(cartId);
		BigDecimal sumYuan = calculateCourseAmount(courses);		
		BigDecimal creditYuan = BigDecimal.ZERO;
		if (useCredit) {
			creditYuan = BigDecimal.valueOf(getCurrentUserCoin(userId).userLearncredit).divide(BigDecimal.valueOf(getStudycoin(request)), BigDecimal.ROUND_HALF_UP, 2);
		}
		result.setSumAmount(sumYuan);
		result.setPromotion(calculateMaxPromotion(courses, sumYuan));

		BigDecimal rest = sumYuan.subtract(result.getPromotion());
		if (creditYuan.compareTo(rest) >= 0) {// 学习币够支付
			result.setUseCredit(rest);
			result.setPayAmount(BigDecimal.ZERO);
		} else {
			result.setUseCredit(creditYuan);
			result.setPayAmount(sumYuan.subtract(result.getPromotion()).subtract(creditYuan));
		}
		return result;
	}

	public BigDecimal calculateCourseAmount(List<DrmCourse> courses) {
		Long sumFen = 0L;
		for (DrmCourse course : courses) {
			sumFen += course.getCurPrice();
		}
		return new BigDecimal(PriceUtils.CoinToYuan(sumFen));
	}

	public BigDecimal calculateMaxPromotion(List<DrmCourse> courses, BigDecimal sumYuan) {
		BigDecimal promotion = BigDecimal.ZERO;
		for (SalesPromotionVo sp : salesPromotionsService.getPromotions()) {
			if (sumYuan.compareTo(new BigDecimal(sp.money)) < 0) {
				continue;
			}
			BigDecimal temp = null;
			if (sp.type == 1) {
				temp = new BigDecimal(sp.reduce);
			} else {
				temp = new BigDecimal(100 - sp.reduce).divide(B100).multiply(sumYuan)
						.setScale(2, BigDecimal.ROUND_HALF_UP);
			}
			if (BigDecimal.ZERO.equals(promotion) || temp.compareTo(promotion) > 0) {
				promotion = temp;
			}
		}
		return promotion;
	}

	//获取当前人的  学习币
	public UserSInfoVo getCurrentUserCoin(Long userId){
		return userService.getUserSInfoById(userId);
	};
	
	//获取当前的促销活动 返回json
	public  String  getCurrentSalesPromotionJson(){
		return  JsonMapper.toJson( salesPromotionsService.getPromotions());
	}
	
	/**
	 * 
	 *  Function:
	 *  功能说明：老师的名称
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2015年3月15日 下午10:01:03
	 *	返回类型: String    
	 *  @param userId
	 *  @return
	 */
	public String getTeacherName(long userId) {
		User u = this.userService.getUserById("" + userId);
		return u.getUserName();
	}
	
	// 立即购买的按钮进入页面
	@RequestMapping(value = "/cart/{courseId}")
	public ModelAndView buyNow(HttpServletRequest request, @Valid @PathVariable Long courseId) {
		ModelAndView view = new ModelAndView("shop/shop");

		Long userId = super.getUserIdInSession(request);
		long cartId = buyCartService.addCourseToCart(userId, courseId, 1);
		List<DrmCourseVo> list = BuyCartService.getCartWithCourse(new Long[] { cartId });

		// 多个课程信息
		view.addObject("courseInfos", list);
		// 增加 活动
		// view.addObject("promotion", getCurrentSalesPromotionJson());
		// 学习币
		view.addObject("coin", getCurrentUserCoin(userId));

		putResourceSrc(view);
		return view;
	}

	/**
	 * 
	 *  Function:
	 *  功能说明：//立即购买的按钮进入页面   ，删除，  该用户 购物车内不，当前的一样的课程
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2015年3月15日 下午7:27:22
	 *	返回类型: ModelAndView    
	 *  @param request
	 *  @param courseId
	 *  @return
	 */
	@RequestMapping(value = "/cart/delete/{cartId}")
	@ResponseBody
	public Map<String, Integer> delete(HttpServletRequest request, @Valid @PathVariable Long cartId) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		try {
			BuyCartService.deleteByCartId(cartId);
			map.put("state", 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 
	 *  Function:
	 *  功能说明：
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2015年3月18日 下午11:51:02
	 *	返回类型: Map<String,Integer>    
	 *  @param request
	 *  @param cartId
	 *  @param courseId
	 *  @return
	 */
	@RequestMapping(value = "/cart/delete/{cartId}/{courseId}")
	@ResponseBody
	public Map<String, Integer> deleteCourse(HttpServletRequest request, @Valid @PathVariable Long cartId
			, @Valid @PathVariable Long courseId
			) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		try {
			BuyCartService.deleteByCartIdCourseId(cartId,courseId);
			map.put("state", 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 
	 *  Function:
	 *  功能说明：
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2015年3月11日 上午12:47:59
	 *	返回类型: ModelAndView    
	 *  @param request
	 *  @return
	 */
	@RequestMapping(value = "/shoppay")
	public ModelAndView shoppay(HttpServletRequest request, @RequestParam(value = "cartId") Long cartId[],
			boolean useCredit) { 
		ModelAndView view = null;

		CalculateAmountVo calculate = calculateAmount(request, cartId, useCredit);
		Long userId = super.getUserIdInSession(request);
		List<DrmCourseVo> lstCart = BuyCartService.getCartWithCourse(cartId);
		DrmBuyOrder order = buyOrderService.addBuyOrder(userId, calculate, lstCart);

		if (calculate.getPayAmount().compareTo(BigDecimal.ZERO) > 0) {// 支付页面
			view = new ModelAndView("shop/shoppay");
			view.addObject("calculate", calculate);
			view.addObject("order", order);
			// view.addObject("orderToken", com.iman.common.util.StringUtils.encodeString(JsonMapper.toJsonNotNull(order)));
			view.addObject("loginName", getSession(request).getUser().getLoginName());
		} else {
			view = new ModelAndView("shop/shopsucces");
			view.addObject("payAmount", calculate.getPayAmount());
		}
		putResourceSrc(view);
		return view;
	}

	@RequestMapping(value = "/gopay", produces = "application/json")
	@ResponseBody
	public Map gopay(HttpServletRequest request, @RequestParam(value = "orderId", required = true) String orderId,
			@RequestParam(value = "payTp", required = false) String payTp) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (payTp == null) {
				payTp = PaymentType.ALIPAY.name();
			}

			DrmBuyOrder buyOrder = buyOrderService.getBuyOrder(orderId);
			PaymentType ptype = PaymentType.valueOf(payTp);
			String payUrl = paymentService.comfirmPay(buyOrder, ptype);

			result.put("code", 1);
			result.put("payUrl", payUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 
	 *  Function:
	 *  功能说明：
	 *	 使用说明：
	 *  @author  wangxiaolei  DateTime 2015年3月11日 上午12:48:26
	 *	返回类型: ModelAndView    
	 *  @param request
	 *  @return
	 */
	@RequestMapping(value = "/shopsucces")
	public ModelAndView shopsucces(HttpServletRequest request,
			@RequestParam(value = "orderId", required = true) String orderId) {
		ModelAndView view = null;

		DrmBuyOrder buyOrder = buyOrderService.getBuyOrder(orderId);
		if (buyOrder.getOrderSt() == 4) {// 支付成功
			view = new ModelAndView("shop/shopsucces");
			view.addObject("payAmount", PriceUtils.CoinToYuan(buyOrder.getPayPrice()));
		} else {
			// TODO 换成支付失败页面--完成
			view = new ModelAndView("shop/shopfail");
		}

		putResourceSrc(view);
		return view;
	}

	@RequestMapping(value = "/shopsure")
	public ModelAndView shopsure(HttpServletRequest request, @RequestParam(value = "cartId") Long cartId[],
			boolean useCredit) {
		ModelAndView view = new ModelAndView("shop/shopsure");
		List<DrmCourse> list = courseInfoService.getCourseByCartIds(cartId);

		// 多个课程信息
		view.addObject("courseInfos", list);
		view.addObject("calculate", calculateAmount(request, cartId, useCredit));

		StringBuffer shoppayUrl = new StringBuffer("useCredit=" + useCredit);
		for (Long cart : cartId) {
			shoppayUrl.append("&cartId=" + cart);
		}
		view.addObject("shoppayUrl", shoppayUrl);

		putResourceSrc(view);
		return view;
	}

	
	
	@RequestMapping(value="/gopay_",produces="application/json")
	@ResponseBody
	public Map gopay_(HttpServletRequest request,
			 @RequestParam(value = "orderId",required=false)  String orderId,
			 @RequestParam(value = "orderToken",required=false) String orderToken,
			 @RequestParam(value = "orderPrice",required=false) Integer orderPrice,
			 @RequestParam(value = "payCorn",required=false) Integer payCorn,
			 @RequestParam(value = "payTp",required=false) String payTp){
		if(payTp==null){
			payTp = PaymentType.ALIPAY.name();
		}
		
		Map<String, Object> result  = new HashMap<String, Object>();
		
		String reToken =  com.iman.common.util.StringUtils.decodeString(orderToken);
		
		DrmBuyOrder order = JsonMapper.toObject(reToken, DrmBuyOrder.class);
		
		
		if(orderId==null || !orderId.equals( order.getOrderId())
			||	
				orderPrice==null || orderPrice.intValue() != order.getPayPrice().intValue()
				 
				||
				payCorn==null || payCorn.intValue() != order.getPayCorn().intValue()	
				
		){
			result.put("code",11);
			return result;
		}
		
		//TODO 这里需要再次验证一下金额
		
		
		String url = paymentService.comfirmPay(order, PaymentType.valueOf(payTp));
		
		if(url==null){
			result.put("code", 10);
			return result;
		}
		
		result.put("code", 0);
		result.put("url", url);
		return result;
		
	}
	 
	
}
